from django import forms
from .models import DataSource
import re

class DataSourceForm(forms.ModelForm):
    class Meta:
        model = DataSource
        fields = ['name', 'description', 'engine', 'host', 'port', 'database', 'user', 'password']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 3}),
            'password': forms.PasswordInput(render_value=True),
        }

    def clean_name(self):
        name = self.cleaned_data.get('name')
        # 获取当前编辑的实例（编辑时存在，创建时为None）
        instance = self.instance  # 由视图在初始化表单时传入（如UpdateView）

        # 检查是否有其他记录使用了相同的name（排除当前实例）
        if DataSource.objects.filter(name=name).exclude(pk=instance.pk if instance else None).exists():
            raise forms.ValidationError("数据源名称已存在")
        # 检查名称是否只包含字母、数字、下划线和连字符
        if not re.match(r'^[a-zA-Z0-9_-]+$', name):
            raise forms.ValidationError('名称只能包含字母、数字、下划线和连字符')
        return name


    def clean_port(self):
        port = self.cleaned_data.get('port')
        if port <= 0 or port > 65535:
            raise forms.ValidationError('端口号必须在1-65535之间')
        return port

class RemoteDatabaseForm(forms.Form):
    DATABASE_ENGINES = [
        ('mysql', 'MySQL'),
        ('postgresql', 'PostgreSQL'),
        ('oracle', 'Oracle'),
        ('sqlite', 'SQLite'),
    ]
    
    name = forms.CharField(label='配置名称', max_length=100)
    engine = forms.ChoiceField(label='数据库类型', choices=DATABASE_ENGINES)
    host = forms.CharField(label='主机地址', max_length=100)
    port = forms.IntegerField(label='端口号')
    database = forms.CharField(label='数据库名称', max_length=100)
    user = forms.CharField(label='用户名', max_length=100)
    password = forms.CharField(label='密码', widget=forms.PasswordInput, required=False)
